library(devtools)
library(ivdoctr)
library(tidyverse)
library(data.table)
library(haven)

# declare path to data
path = ""
# declare path to output
outpath = ""

# read main data in 
dt <- "{path}/fascism_db.dta" %>% str_glue() %>% read_dta() %>% 
  
  # standardize and rename vars
  mutate_at(vars(fascist_violence:strike_agr_1920, lpop1911:volunteers1866_pop, rain1918:rain_var), 
            list(std = ~ (.-mean(., na.rm = TRUE))/sd(., na.rm = TRUE))) %>% 
  rename_at(vars(ends_with("_std")), ~paste0("z_", gsub("_std", "", .)) )
  

# controls:
prov_ctr = dt %>% select(starts_with("province")) %>% names()
reg_d = dt %>% select(starts_with("d_reg")) %>% names()
demo=c("z_lpop1911","z_lpop2","z_lpop3","z_lpop4","z_sh_pop_1911_be6")
geo=c("z_larea","z_centre_alt","z_max_alt")
corps=c("z_ard_vol_pop6m","z_cruent_d","z_veterans74_95","z_veterans96_00","z_army_suppliers_d")
rural=c("z_dlab","z_shcrop","z_landlord_ass")
urban=c("z_ind_workers","z_ind_firms","z_literacy","z_elites","z_bourgeoisie")
full_ctr=c(demo,geo,"z_psu1913_vv",corps,rural,urban,prov_ctr,reg_d)


# Looping over outcome variables:
outcomes <- c("z_fascist1924_vv","z_fascist_violence","z_fascist_branch","z_fascist1921_vv")

set.seed(1111)

for(outcome in outcomes){
  
  var_2_keep<-c(outcome, "z_psu1919_vv", "z_foots_pop6m", full_ctr)
  Data = dt %>% select(var_2_keep) %>% na.omit(.)
  
  K1 <- ivdoctr:::makeExample(outcome, "z_psu1919_vv", "z_foots_pop6m", Data, controls =full_ctr , robust = TRUE,
                              r_TstarU_restriction =  matrix(c(-0.1, -0.9), nrow = 1), k_restriction= matrix(c(0.5, 1), nrow = 1), n_draws = 5000,
                              n_RF_draws = 1000, n_IS_draws = 1000, resample = FALSE, outcome)
  
  ivdoctr:::makeTable(paste0(outpath, "/Ditraglia_", outcome,".tex"), binary = FALSE, K1)
  
}
